#ifndef MERGESORT_H
#define MERGESORT_H

void aprint(char *n, int *a, int s)
{
    printf("%s of size %i is:", n, s);
    int i;
    for (i=0; i < s; i++)
    {
        printf("%i, ", a[i]);
        fflush(stdout);
    }
    printf("\n");
}

//Receive to arrays, merge them in ascending order, and return the result
//receive two arrays and their's sizes
void mergeArrays( int *array1, int *array2, int size1, int size2, int* dest)
{
    //verify if the parameters are valid
    if ( array1 == NULL || array2 == NULL ) return;

    int i = 0 ,j = 0,k = 0;

    while ( k < size1 + size2 )
    {
       if ( array1[i] < array2[j] )
            if ( i < size1 )
                dest[k++] = array1[i++];
            else
                dest[k++] = array2[j++];
        else
            if ( j < size2 )
                dest[k++] = array2[j++];
            else
                dest[k++] = array1[i++];
    }

    for( i = 0; i < size1 + size2; i++)
        array1[i] = dest[i];

}//end mergeArrays

//Receive a array and it's boundaries. Return a sorted array.
void mergeSort( int* a, int s )
{
    //check the parameters
    if ( a == NULL )
    {
        printf("Invalid parameters\n");
        abort();
    }//end if

    if ( s > 1)
    {
        //determines where to split
        int s1 = s - s / 2;
        int s2 = s - s1;

        //start spliting the array
        int *a1 = a, *a2 = &a[s1];
        mergeSort( a, s1 );
        mergeSort( &a[s1], s2 );

        int rdest[s1+s2];

        mergeArrays(a1, a2, s1, s2, rdest);
    } //end if

}//end mergeSort

#endif
